//
//  BYChangeCityViewController.m
//  ZhiHuiLiJiang
//
//  Created by Work on 2018/12/17.
//  Copyright © 2018年 WisdomLijiang. All rights reserved.
//

#import "BYChangeCityViewController.h"
#import "SearchTabelFootView.h"
#import "BYHotCityView.h"
#import "CoreLocation/CoreLocation.h"

@interface BYChangeCityViewController ()<SearchTabelFootViewDelegate,BYHotCityViewDelegate,CLLocationManagerDelegate>

@property (nonatomic ,strong)  NSMutableArray *dataArray;

//历史搜索数组
@property (nonatomic ,strong)  NSMutableArray *HistoryArray;

@property (nonatomic ,strong)  UICollectionView *collectioneView;

@property (nonatomic ,strong)  UILabel *titleLabel;

@property (nonatomic ,strong)  UIButton *CityLabel;

@property (nonatomic ,strong)  UIButton *CityBtn;

@property (nonatomic ,strong)  SearchTabelFootView *HisView;

@property (nonatomic ,strong)  BYHotCityView *allView;

@property (nonatomic ,strong)  UILabel *AllLabel;

@property (strong, nonatomic) CLLocationManager* locationManager;

@property (copy, nonatomic) NSString* cuCity;

@end

@implementation BYChangeCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creartArray];
    [self startLocation];

    self.HistoryArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SEARCHCOMP]];
    [self addView];

    if (self.HistoryArray.count >0) {
        [self.HisView creatView:self.HistoryArray];
    }

}
-(void)creartArray{
    self.HistoryArray = [[NSMutableArray alloc]init];
    self.dataArray = [[NSMutableArray alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startLocation) name:BYEnterForeground object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    if (!self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = YES;
    }
}
- (void)addView{
    self.view.backgroundColor = [UIColor whiteColor];
    BY_kWeakSelf(ws);
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(BY_ScreenWidth/4.0, BY_StatusBar_H, BY_ScreenWidth / 2.0, 44);
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"切换城市";
    [self.view addSubview:titleLabel];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *backImage = [UIImage imageNamed:@"mainIcon_back"] ;
    [backBtn setImage:backImage forState:UIControlStateNormal];
    [backBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [ws.navigationController popViewControllerAnimated:YES];
    }];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).offset(10);
        make.centerY.equalTo(titleLabel.mas_centerY);
        make.height.width.offset(30);
    }];
    UIView *LineView = [[UIView alloc]init];
    LineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:LineView];
    [LineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left);
        make.right.equalTo(ws.view.mas_right);
        make.top.equalTo(titleLabel.mas_bottom);
        make.height.mas_equalTo(0.5);
    }];
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = H14;
    self.titleLabel.textColor = RGBA(152, 152, 152, 1);
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.text =@"你所在的地区";
    [self.titleLabel sizeToFit];
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).offset(12);
        make.top.equalTo(LineView.mas_bottom).offset(12);
    }];
    self.CityLabel = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.CityLabel setTitleColor:RGBA(40,40,40, 1) forState:UIControlStateNormal];
    self.CityLabel.layer.borderWidth =0.5;
    self.CityLabel.layer.borderColor = RGBA(152, 152, 152, 1).CGColor;
    self.CityLabel.titleLabel.font = H17;
    self.CityLabel.layer.masksToBounds = YES;
    self.CityLabel.layer.cornerRadius = 4;
    [self.CityLabel addTarget:self action:@selector(CityLabelClick) forControlEvents:UIControlEventTouchUpInside];

    [self.CityLabel sizeToFit];
    [self.view addSubview:self.CityLabel];
    [self.CityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).offset(12);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(12);
        make.size.mas_equalTo(CGSizeMake(110, 36));
    }];
    self.CityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.CityBtn setTitle:@"定位" forState:UIControlStateNormal];
    [self.CityBtn setTitleColor:RGBA(40,40,40, 1) forState:UIControlStateNormal];
    [self.CityBtn setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    self.CityBtn.imageEdgeInsets = UIEdgeInsetsMake(0, BY_Width(-50), 0, BY_Width(60));
    self.CityBtn.titleEdgeInsets = UIEdgeInsetsMake(0, BY_Width(-100), 0, 0);
    [self.CityBtn addTarget:self action:@selector(cityClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.CityBtn];
    [self.CityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.CityLabel.mas_right).offset(12);
        make.centerY.equalTo(ws.CityLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(110, 36));
    }];

    [self.view addSubview:self.HisView];
    [self.HisView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.CityLabel.mas_bottom).offset(12);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        if (self.HistoryArray.count==0) {
            make.height.equalTo(@12);
        }
        if (self.HistoryArray.count<=2) {
            make.height.equalTo(@72);

        }
        else{
            make.height.equalTo(@130);

        }
    }];

    self.AllLabel = [[UILabel alloc]init];
    self.AllLabel.font = H14;
    self.AllLabel.textColor = RGBA(152, 152, 152, 1);
    self.AllLabel.numberOfLines = 0;
    self.AllLabel.text =@"服务开通区";
    [self.AllLabel sizeToFit];
    [self.view addSubview:self.AllLabel];
    [self.AllLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).offset(12);
        make.top.equalTo(self.HisView.mas_bottom).offset(12);
    }];
    
    [self.view addSubview:self.allView];
    [self.allView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left);
        make.right.equalTo(ws.view.mas_right);
        make.top.equalTo(self.AllLabel.mas_bottom);
        make.height.equalTo(@108);
    }];

    
}

-(SearchTabelFootView *)HisView{
    
    if (!_HisView) {
        _HisView = [[SearchTabelFootView alloc]init];
        _HisView.delegate = self;
    }
    return _HisView;
}
-(BYHotCityView *)allView{
    if (!_allView) {
        _allView = [[BYHotCityView alloc]init];
        _allView.delegate =self;
    }
    return _allView;

}

-(void)BtnClckStr:(NSString *)str{
    if (![self.HistoryArray containsObject: str]) {
        [self.HistoryArray addObject:str];
        NSArray * array = [NSArray arrayWithArray:self.HistoryArray];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:array forKey:SEARCHCOMP];
    }
    [self LocationCity:str];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchViewClick:(NSString *)str{
    [self LocationCity:str];
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)LocationCity:(NSString *)str{
    
    if ([str isEqualToString:@"丽江市"]) {
        self.latitude = [@"26.87210" doubleValue];
        self.longitude =[@"100.25000" doubleValue];
    }
    if ([str isEqualToString:@"古城区"]) {
        self.latitude = [@"26.87591" doubleValue];
        self.longitude =[@"100.22635" doubleValue];

    }
    if ([str isEqualToString:@"玉龙县"]) {
        self.latitude = [@"26.82111" doubleValue];
        self.longitude =[@"100.23521" doubleValue];

    }
    if ([str isEqualToString:@"永胜县"]) {
        self.latitude = [@"26.68432" doubleValue];
        self.longitude =[@"100.75112" doubleValue];

    }
    if ([str isEqualToString:@"华坪县"]) {
        self.latitude = [@"26.62883" doubleValue];
        self.longitude =[@"101.26585" doubleValue];

    }
    if ([str isEqualToString:@"宁蒗县"]) {
        self.latitude = [@"27.28213" doubleValue];
        self.longitude =[@"100.85213" doubleValue];

    }
    
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    [useDef setObject:[NSString stringWithFormat:@"%f",self.latitude] forKey:@"latitude"];
    [useDef setObject:[NSString stringWithFormat:@"%f",self.longitude] forKey:@"longitude"];
    [useDef synchronize];

    self.clickStr(str,self.latitude,self.longitude);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)startLocation{
    if ([self determineWhetherTheAPPOpensTheLocation]) {
//    if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许
        
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;//遵循代理
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        self.locationManager.distanceFilter = 10.0f;
        
        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8以上版本定位需要）
        
        [self.locationManager startUpdatingLocation];//开始定位
        
    }else{//不能定位用户的位置的情况再次进行判断，并给与用户提示
        
        //1.提醒用户检查当前的网络状况
        
        //2.提醒用户打开定位开关
        [self AlertWithTitle:@"智慧丽江-需要根据您的位置获取天气信息" message:@"请在iPhone的“设置->隐私->定位服务”中打开定位服务，并允许智慧丽江使用定位服务。" andOthers:@[@"不允许",@"去设置"] animated:YES action:^(NSInteger index) {
            if (index==1) {
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                }
                
            }
        }];
    }
    
}

-(BOOL)determineWhetherTheAPPOpensTheLocation{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] ==kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] ==kCLAuthorizationStatusAuthorizedAlways)) {
        return YES;
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        return NO;
    }else{
        return NO;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    //当前所在城市的坐标值
    CLLocation *currLocation = [locations lastObject];
    
    self.latitude =currLocation.coordinate.latitude;
    self.longitude =currLocation.coordinate.longitude;
    
    //根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *address = [placemark addressDictionary];
            
            self.cuCity =[address objectForKey:@"City"];
            [self.CityLabel setTitle:[address objectForKey:@"City"] forState:UIControlStateNormal];

        }
        
    }];
    
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    if ([error code] == kCLErrorDenied){
        //访问被拒绝'
        
    }
    if ([error code] == kCLErrorLocationUnknown) {
        //无法获取位置信息
        
    }
}
-(void)cityClick{
}
-(void)CityLabelClick{
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    [useDef setObject:[NSString stringWithFormat:@"%f",self.latitude] forKey:@"latitude"];
    [useDef setObject:[NSString stringWithFormat:@"%f",self.longitude] forKey:@"longitude"];

    [useDef synchronize];
    [self LocationCity:self.cuCity];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
